<?php
/**
 * 	Bushido
 *
 * @category   Bushido
 * @package    Bushido_Controller_Action
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes
 * @author Nathan Keyes
 * @version    $Id: Action.php 7 2009-11-14 22:42:08Z nkeyes $
 */	
require_once('Zend/Controller/Action.php');

/**
 * Implements security features:
 * Page hit tracking and requiring of authentication
 *
 * @category   Bushido
 * @package    Bushido_Controller_Action
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes

 */
class Bushido_Controller_Action extends Zend_Controller_Action
{
	/**
	 * Whether or not to require autheentication
	 * @var Boolean
	 */
	protected $_requiresAuth = true;
	protected $_logSelf = true;
	protected $_appconfig;
	//protected $_acl;
	
	/**
	 * (non-PHPdoc)
	 * @see library/Zend/Controller/Zend_Controller_Action#init()
	 */
	public function init()
	{
		//echo __FILE__ . ' line ' . __LINE__ . ': ' . $this->_requiresAuth . '<br />';
		$this->_requiresAuth = true;
		$this->_logSelf = true;
		$this->_appconfig = Zend_Controller_Front::getInstance()->getParam('appconfig');
		//$this->_acl = Bushido_App::session()->acl;
		//echo __FILE__ . ' line ' . __LINE__ . ': ' . $this->_requiresAuth . '<br />';
		
	}
	
	/**
	 * Does security checks before dispatching the request
	 * 
	 * @return void
	 */
	public function preDispatch()
	{
		
		//store the params
		Zend_Registry::set('params', $this->_getAllParams());
		
		if(/*(boolean)$this->_appconfig['requirelogin'] && */$this->_requiresAuth)
		{
			if(!Zend_Auth::getInstance()->hasIdentity())
			{
				$attemptedRequest = array
				(
					'controller' => $this->getRequest()->getControllerName(),
					'action' => $this->getRequest()->getActionName(),
					'module' => $this->getRequest()->getModuleName(),
					'params' => Zend_Registry::get('params')
				);
				$session = Bushido_App::session();
				$session->attemptedRequest = $attemptedRequest;
				if($this->_hasParam('useLayout') && $this->_getParam('useLayout') == 'false')
				{
					$this->_helper->redirector('index','user', 'default', array('useLayout' => 'false'));
				}
				else
				{
					$this->_helper->redirector('index','user', 'default');
				}
			}
			
			
		}
		elseif(!isset($session->userInfo) && !Zend_Auth::getInstance()->hasIdentity())
		{
			//echo "no userInfo && no identity";exit;
			/*
			$userInfo = array();
			$userInfo['uid'] = 'Nathan Keyes';
			$userInfo['bushido_user_id'] = '334689';
			$userInfo['teamId'] = '50';
			$session = Bushido_App::session();
			$session->userInfo = $userInfo;
			Bushido_App::setUserRoles($userInfo);
			*/
		}
		//exit;
		
		if($this->_hasParam('useLayout') && $this->_getParam('useLayout') == 'false')
		{
			$this->_helper->layout->disableLayout();
			
		}
		
		$this->view->doctype('XHTML1_STRICT');
		$this->view->appconfig = Zend_Controller_Front::getInstance()->getParam('appconfig');
		//$this->_logTraffic();
	
	}
	
	
	/**
	 * 
	 * @param $userInfo
	 * @param $resourceId
	 * @return void
	 */
	protected function challegeAccess($userInfo, $resourceId)
	{
		if($this->_appconfig['requirelogin'] && (!isset($userInfo['uid'])/* || !$this->_acl->isAllowed($userInfo['uid'], $resourceId)*/))
		{
			throw new Zend_Acl_Exception('User "' . $userInfo['uid'] . '" does not have access to resource "' . $resourceId . '"');
		}
	}
	
	/**
	 * 
	 * @param $roles
	 * @return void
	 */
	protected function _assertRoles($roles)
	{
		if(!(Bushido_DbTable_User::hasRole(Bushido_App::session()->userInfo['bushido_user_id'], $roles)))
		{
			throw new Zend_Acl_Exception();
		}
	}
	
	
	public function postDispatch()
	{
		$this->_logTraffic();
	}
	
	protected function _logTraffic()
	{
		//Zend_Debug::dump('traffic');exit;
		$frontController = Zend_Controller_Front::getInstance();
		$request = $frontController->getRequest();
		$response = $frontController->getResponse();
		
		$adapter = Bushido_Db_Table::getAdapter();
		
		
		
		$trafficLog = array
		(
			'module_name' => $request->getModuleName(),
			'controller_name' => $request->getControllerName(),
			'action_name' => $request->getActionName(),
			'method' => $request->getMethod(),
			'status' => $response->getHttpResponseCode(),
			'ip_address' => $_SERVER['REMOTE_ADDR'],
			'user_agent' => $_SERVER['HTTP_USER_AGENT'],
			'uri' => $request->getRequestUri(),
			'params' => print_r($request->getParams(), true),
			'timestamp' => new Zend_Db_Expr('NOW()'),
			
		);
		
		$user = Bushido_App::getUser();
		
		if($user)
		{
			$trafficLog['bushido_user_id'] = $user->bushido_user_id;
		}
		//Zend_Debug::dump($trafficLog, '$trafficLog');
		
		$adapter->insert
		(
			'traffic_log',
			$trafficLog
		);
	}
}